JavaScript 设计模式之代理模式

Author Avatar
Klein 8月 28, 2018

介绍

  • 使用者无权访问目标对象
  • 中间加代理,通过代理做授权和控制

例子

  • 科学上网
  • 明星经纪人

演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class RealImg {
constructor(fileName) {
this.fileName = fileName
// 模拟初始化即从硬盘中加载,模拟
this.loadFromeDisk()
}
display() {
console.log('display...' + this.fileName);
}
loadFromeDisk() {
console.log('loadFromeDisk...');
}
}

class ProxyImg {
constructor(fileName) {
this.realImg = new RealImg(fileName)
}
display() {
this.realImg.display()
}
}


// 测试
let client = new ProxyImg('1.png')
client.display()

场景

网页事件代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<body>
<div id="app">
<a href="#">a1</a>
<a href="#">a2</a>
<a href="#">a3</a>
<a href="#">a4</a>
<a href="#">a5</a>
</div>
<button id="button"></button>
<script>
let div1 = document.getElementById('app')
div1.addEventListener('click', function(e) {
var target = e.target
if (target.nodeName === 'A') {
console.log(target.innerHTML);
}
})
</script>
</body>

jQuery $.proxy

1
2
3
4
5
6
7
8
9
10
$('#div1').click(function() {
// this 符合预期
$(this).addClass('red')
})
$('#div1').click(function() {
setTimeout(function() {
// this 不符合预期
$(this).addClass('red')
}, 1000)
})

通常我们这样解决:

1
2
3
4
5
6
7
8

$('#div1').click(function() {
var _this = this
setTimeout(function() {
// this 符合预期
$(_this).addClass('red')
}, 1000)
})

虽说箭头函数也可以解决。但是总有不适合用箭头函数的情况,这时候推荐用 $.proxy 解决,这样就少定义一个变量。

1
2
3
4
5
6
$('#div1').click(function() {
setTimeout($.proxy(function() {
// this 符合预期
$(this).addClass('red')
}, this), 1000);
})

ES6 proxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 明星
let star = {
name: '张XX',
age: 25,
phone: '13910733521'
}

// 经纪人
let agent = new Proxy(star, {
get: function (target, key) {
if (key === 'phone') {
// 返回经纪人自己的手机号
return '18611112222'
}
if (key === 'price') {
// 明星不报价,经纪人报价
return 120000
}
return target[key]
},
set: function (target, key, val) {
if (key === 'customPrice') {
if (val < 100000) {
// 最低 10w
throw new Error('价格太低')
} else {
target[key] = val
return true
}
}
}
})

// 主办方
console.log(agent.name)
console.log(agent.age)
console.log(agent.phone)
console.log(agent.price)

// 想自己提供报价(砍价,或者高价争抢)
agent.customPrice = 150000
// agent.customPrice = 90000 // 报错:价格太低
console.log('customPrice', agent.customPrice)

设计原则验证

  • 代理类和目标类分离,隔离开目标类和使用类
  • 符合开放封闭原则